package colopllet.colopl.pc.request;

import gae.util.http.client.Cookie;
import gae.util.http.client.Header;
import gae.util.http.client.HttpRequest;
import gae.util.http.client.HttpResponse;
import gae.util.http.client.Parameter;
import colopllet.colopl.pc.ColoplPCRequestException;
import colopllet.colopl.pc.response.PCTopLoginResponse;
import colopllet.colopl.pc.session.ColoplSession;

public class PCTopLoginRequest extends AbstractColoplRequest<PCTopLoginResponse> {

    protected final static String PC_TOP_URL = "http://pl.colopl.jp/c/c/pc";
    
    private String submit;
    private String hdb;
    
    public PCTopLoginRequest(ColoplSession session, String submit, String hdb) {
        this.session = session;
        this.submit = submit;
        this.hdb = hdb;
    }
    
    @Override
    public HttpRequest createRequest() throws ColoplPCRequestException {
        Parameter param = new Parameter();
        param.set("username", session.getUsername());
        param.set("password", session.getPassword());
        param.set("submit", submit);
        param.set("hdb", hdb);
        param.set("submit.x", "27");
        param.set("submit.y", "21");
        
        Cookie reqCookie = new Cookie();
        reqCookie.addParam("JSESSIONID", session.getJsessionid(), 0);
        Header reqHeader = getDefaultRequestHeader();
        reqHeader.setCookie(reqCookie);
        
        HttpRequest req = new HttpRequest("POST", PC_TOP_URL);
        req.setParameter(param);
        req.setHeader(reqHeader);
        
        return req;
    }

    @Override
    public PCTopLoginResponse parseResponse(HttpResponse res) throws ColoplPCRequestException {
        PCTopLoginResponse result = new PCTopLoginResponse();
        result.setRes(res);
        
        Header resHeader = res.getHeader();
        Cookie resCookie = resHeader.getCookie();
        session.setJsessionid(resCookie.getParam("JSESSIONID"));
        session.setPt(resCookie.getParam("pt"));
        
        return result;
    }

}
